<template>
	<view class="detail-box u-skeleton">
		<u-navbar back-text="" :title="bookDetail.name" :border-bottom="false" :background="navBarBackground"
		 :back-icon-color="navBarColor" :title-color="navBarTextColor">
			<u-icon name="more-dot-fill" class="u-skeleton-rect" :color="navBarColor" size="44" @click="handleToShare"></u-icon>
		</u-navbar>

		<view class="detail-bg" :style="'background-image:url('+ bookDetail.image +')'"></view>
		<view class="detail-wrap"></view>

		<view class="detail-content">
			<view class="detail-top">
				<view class="detail-left">
					<view class="detail-main u-skeleton-rect">
						<view class="detail-name">{{bookDetail.name}}</view>
						<view class="detail-info">
							<view class="detail-writer">{{bookDetail.writer}}</view>
							<text class="detail-over">{{bookDetail.is_over}} | {{bookDetail.type}}</text>
						</view>
					</view>
					<view class="detail-new  u-skeleton-rect" @click="handleToNew">
						<text class="u-line-1">{{bookDetail.new_chapter||'暂无更新章节'}}</text>
						<u-icon name="arrow-right" color="#fff" size="28"></u-icon>
					</view>
				</view>
				<u-image class="u-skeleton-fillet" width="144rpx" height="194rpx" border-radius="16" :src="bookDetail.image" mode="cover"
				 :fade="true" duration="450">
					<u-loading slot="loading"></u-loading>
				</u-image>
			</view>
			<view class="detail-intro  u-skeleton-rect">
				<view>简介：</view>
				<!-- 			<u-collapse>
					<u-collapse-item :title="bookDetail.intro">
						{{bookDetail.intro}}
					</u-collapse-item>
				</u-collapse> -->
				<view class="">{{bookDetail.intro}}</view>
			</view>
		</view>

		<view class="detail-list">
			<view class="list-nav u-skeleton-rect">
				<u-icon :name="topFlag?'arrow-up':'arrow-down'" color="#061B41" size="28" @click="handleToTop"></u-icon>
				<text>目录</text>
				<text @click="handleToReverse">{{reverseFlag ? '正序':'倒序'}}</text>
			</view>
			<scroll-view class="list-content" scroll-y show-scrollbar @scrolltolower="loadMoreChapter" :scroll-top="chapterListScrollTop"
			 @scroll="scroll">
				<view :class="lastReadChapterIndex == index ? 'active-item' : lastReadChapterIndex > index ? 'read-item':'list-item'"
				 v-for="(item, index) in chapterList" :key="index" @click="handleToCurrentChapter(item.book_id,item.id)">
					<view class="u-line-1" style="width: 90%;">{{item.title}}</view>
					<u-icon v-if="lastReadChapterIndex == index" name="play-circle-fill" color="#92C8FF" size="36" style="position: absolute;right: 0;width: 10%;"></u-icon>
					<u-icon v-if="lastReadChapterIndex > index" name="checkmark-circle-fill" color="rgba(6,27,65,0.75)" size="34"
					 style="position: absolute;left: -52rpx;width: 10%;"></u-icon>
				</view>
				<u-loadmore :status="status" margin-top="20" margin-bottom="20" :load-text="loadText" />
			</scroll-view>
		</view>

		<view class="detail-bottom u-skeleton-rect">
			<text class="add-shelf" @click="handleAddBookShelf">{{flag?'撤出书架':'加入书架'}}</text>
			<text class="read-start" @click="handleToRead(bookDetail.id,bookDetail.first_chapter_id)">开始阅读</text>
		</view>
		<u-skeleton :loading="skeLoading" :animation="true" bg-color="#F5F8FC" :border-radius="40"></u-skeleton>
		<u-toast ref="uToast" />
	</view>
</template>

<script>
	import {
		getChapterDetail,
		getChapterList
	} from "../../api/chapter";
	import {
		addBookToShelf,
		delBookFromShelf,
		updateBookShelfList,
		getBookShelfList
	} from '../../api/shelf'
	export default {
		name: 'detail',
		data() {
			return {
				flag: false,
				topFlag: true,
				reverseFlag: true,
				bookDetail: {},
				chapterList: [],
				chapterCount: 0,
				bookShelfId: 0,
				navBarBackground: {
					'background': 'rgba(255,255,255,0)'
				},
				navBarColor: 'rgba(255,255,255,0.65)',
				navBarTextColor: 'rgba(0,0,0,0)',
				currentPage: 1,
				pageSize: 50,
				lastPage: 10,
				status: 'loadMore',
				orderBy: 1,
				chapterListScrollTop: 0,
				old: {
					chapterListScrollTop: 0
				},
				lastReadChapterId: 0,
				lastReadChapterIndex: 0,
				loadText: {
					loadmore: '点击或上拉加载更多',
					loading: '努力加载中',
					nomore: '实在没有了'
				},
				skeLoading: true
			}
		},
		onLoad(option) {
			this.bookId = option.id;
			this.init(this.bookId);
		},
		onPageScroll(e) {
			if (e.scrollTop === 0) {
				this.navBarBackground = {
					'background': 'rgba(255,255,255,0)'
				};
				this.navBarColor = 'rgba(255,255,255,0.65)';
				this.navBarTextColor = 'rgba(0,0,0,0)';
				this.topFlag = true
			} else {
				if (e.scrollTop < 100) {
					this.navBarBackground = {
						'background': `rgba(255,255,255,${e.scrollTop / 100})`
					};
					this.navBarColor = `rgba(0,0,0,${e.scrollTop / 100})`;
					this.navBarTextColor = `rgba(0,0,0,${e.scrollTop / 100})`;
				} else {
					this.navBarBackground = {
						"background": "rgba(255,255,255,1)"
					};
					this.navBarColor = 'rgba(0,0,0,1)';
					this.navBarTextColor = 'rgba(0,0,0,1)';
					this.topFlag = false;
				}
			}
		},
		onReachBottom() {
			this.topFlag = false;
		},
		onShow() {
			this.handleGetBookShelf(this.bookId);
			this.getLastReadChapter();
		},
		methods: {
			async init(id) {
				await this.getChapterDetail(id);
				await this.getChapterList(id);
				await this.handleGetBookShelf(id);
				await this.setBookList();
				setTimeout(() => {
					this.skeLoading = false;
				}, 500);
				this.getLastReadChapter();
			},
			// 获取书本详情
			getChapterDetail(id) {
				return new Promise((resolve, reject) => {
					getChapterDetail({
						id
					}).then((res) => {
						this.bookDetail = res.data;
						resolve("ok");
					});
				});
			},
			// 获取章节列表（分页）
			getChapterList() {
				this.status = 'loading'
				if (this.currentPage == this.lastPage) {
					this.status = 'nomore'
					return
				}
				return new Promise((resolve, reject) => {
					getChapterList({
						id: this.bookId,
						page: this.currentPage,
						pageSize: this.pageSize,
						orderBy: this.orderBy
					}).then((res) => {
						this.chapterList = this.chapterList.concat(res.data.data)
						if (res.data.total == 0) {
							this.$refs.uToast.show({
								title: '未找到章节列表',
								type: 'error',
								position: 'top'
							});
							this.status = 'loadmore'
						} else {
							this.currentPage += 1;
							this.chapterCount = res.data.total;
							this.lastPage = res.data.last_page;
						}
						resolve("ok");
					});
				});
			},
			// 章节加载
			loadMoreChapter: _.throttle(function() {
				this.getChapterList()
			}, 500),
			// 滚动
			scroll(e) {
				this.old.chapterListScrollTop = e.detail.scrollTop
			},
			// 排序方式
			handleToReverse: _.debounce(function() {
				this.reverseFlag = !this.reverseFlag;
				if (this.reverseFlag) {
					this.orderBy = 1;
				} else {
					this.orderBy = 2;
				}
				this.chapterList = [];
				this.currentPage = 1;
				this.chapterListScrollTop = this.old.chapterListScrollTop
				this.$nextTick(() => {
					this.chapterListScrollTop = 0;
				});
				this.getChapterList();
			}, 500, {
				'leading': true,
				'trailing': false
			}),
			// 滚动到顶部
			handleToTop() {
				let _scrollTop = 0
				if (this.topFlag) {
					_scrollTop = 10000;
				}
				uni.pageScrollTo({
					duration: 100,
					scrollTop: _scrollTop
				})
			},
			// 去最新章节
			handleToNew() {
				if (!this.bookDetail.new_chapter) return;
				uni.navigateTo({
					url: `/pages/read/read?id=${this.bookDetail.id}&chapter_id=${this.bookDetail.last_chapter_id}`,
				});
			},
			// 开始阅读
			handleToRead(id, chapter_id) {
				if (this.chapterList.length === 0) {
					this.$refs.uToast.show({
						title: '未找到章节列表,不能阅读该书!',
						type: 'error',
						position: 'top'
					});
					return;
				};
				let _chapterId = 0
				if (this.lastReadChapterId === 0 || this.lastReadChapterId === undefined) {
					_chapterId = chapter_id;
				} else {
					_chapterId = this.lastReadChapterId;
				}
				uni.navigateTo({
					url: `/pages/read/read?id=${id}&chapter_id=${_chapterId}`,
				});
			},
			handleToCurrentChapter(id, chapter_id) {
				uni.navigateTo({
					url: `/pages/read/read?id=${id}&chapter_id=${chapter_id}`,
				});
			},
			// 查询书架缓存
			handleGetBookShelf(id) {
				if (this.access_token) {
					let header = {
						Authorization: 'Bearer ' + this.access_token
					}
					getBookShelfList(header).then(res => {
						let bookshelfList = [];
						if (res.code == 200) {
							bookshelfList = res.data.bookList;
						}
						bookshelfList.forEach(item => {
							if (item.book_id == id) {
								this.flag = true;
								this.bookShelfId = item.book_shelf_id;
							}
						})
					})
				} else {
					try {
						let bookShelf = uni.getStorageSync("bookShelf");
						if (bookShelf) {
							let _bookShelf = JSON.parse(bookShelf);
							if (_bookShelf[id]) {
								this.flag = true;
							}
						}
					} catch (e) {
						console.log(e);
					}
				}
			},
			// 加入or撤出书架
			handleAddBookShelf: _.debounce(function() {
				if (this.chapterList.length === 0) {
					this.$refs.uToast.show({
						title: '未找到章节列表,不能加入书架!',
						type: 'error',
						position: 'top'
					});
					return;
				}
				if (this.access_token) {
					if (this.flag) { // 撤出
						delBookFromShelf({
							Authorization: 'Bearer ' + this.access_token
						}, {
							'bookShelfId': this.bookShelfId
						}).then(res => {
							this.flag = false;
							this.$refs.uToast.show({
								title: '成功撤出书架',
								type: 'success',
								position: 'top'
							})
						})
					} else { // 加入
						addBookToShelf({
							Authorization: 'Bearer ' + this.access_token
						}, {
							'bookId': this.bookDetail.id,
							'lastReadChapter': this.lastReadChapterId === 0 ? this.chapterList[0].id : this.lastReadChapterId,
							'index': this.lastReadChapterIndex ? this.lastReadChapterIndex : 0
						}).then(res => {
							this.flag = true;
							this.$refs.uToast.show({
								title: '成功加入书架',
								type: 'success',
								position: 'top'
							})
						})
					}
				} else {
					if (this.flag) {
						let bookShelf = uni.getStorageSync("bookShelf");
						if (bookShelf) {
							let _bookShelf = JSON.parse(bookShelf);
							if (_bookShelf[this.bookDetail.id]) {
								delete _bookShelf[this.bookDetail.id];
								uni.setStorageSync("bookShelf", JSON.stringify(_bookShelf));
								this.flag = false;
								this.$refs.uToast.show({
									title: '成功撤出书架',
									type: 'success',
									position: 'top'
								})
							}
						}
					} else {
						let bookShelf = uni.getStorageSync("bookShelf");
						let _bookShelf = bookShelf ? JSON.parse(bookShelf) : {};
						_bookShelf[this.bookDetail.id] = {
							index: this.lastReadChapterIndex ? this.lastReadChapterIndex : 0,
							last_read_chapter: this.lastReadChapterId === 0 ? this.chapterList[0].id : this.lastReadChapterId,
							book_id: this.bookDetail.id,
							chapterCount: this.chapterCount,
							chapter_id: this.bookDetail.first_chapter_id,
							name: this.bookDetail.name,
							type: this.bookDetail.type,
							writer: this.bookDetail.writer,
							is_over: this.bookDetail.is_over,
							image: this.bookDetail.image
						};
						uni.setStorageSync("bookShelf", JSON.stringify(_bookShelf));
						this.flag = true;
						this.$refs.uToast.show({
							title: '成功加入书架',
							type: 'success',
							position: 'top'
						})
					}
				}
			}, 500, {
				'leading': true,
				'trailing': false
			}),
			// 设置书本缓存
			setBookList() {
				let bookList = uni.getStorageSync("bookList");
				if (bookList) {
					let _bookList = JSON.parse(bookList);
					if (_bookList[this.bookDetail.id]) {
						_bookList[this.bookDetail.id].id = this.bookDetail.id;
						_bookList[this.bookDetail.id].chapterCount = this.chapterCount;
						_bookList[this.bookDetail.id].name = this.bookDetail.name;
						_bookList[this.bookDetail.id].type = this.bookDetail.type;
						_bookList[this.bookDetail.id].writer = this.bookDetail.writer;
						_bookList[this.bookDetail.id].is_over = this.bookDetail.is_over;
						_bookList[this.bookDetail.id].image = this.bookDetail.image;
						_bookList[this.bookDetail.id].first_chapter_id = this.bookDetail.first_chapter_id;
						_bookList[this.bookDetail.id].last_chapter_id = this.bookDetail.last_chapter_id;
						_bookList[this.bookDetail.id].intro = this.bookDetail.intro;
					} else {
						_bookList[this.bookDetail.id] = {
							id: this.bookDetail.id,
							chapterCount: this.chapterCount,
							name: this.bookDetail.name,
							type: this.bookDetail.type,
							writer: this.bookDetail.writer,
							is_over: this.bookDetail.is_over,
							image: this.bookDetail.image,
							first_chapter_id: this.bookDetail.first_chapter_id,
							last_chapter_id: this.bookDetail.last_chapter_id,
							intro: this.bookDetail.intro
						};
					}
					uni.setStorageSync("bookList", JSON.stringify(_bookList));
				} else {
					let _bookList = {};
					_bookList[this.bookDetail.id] = {
						id: this.bookDetail.id,
						chapterCount: this.chapterCount,
						name: this.bookDetail.name,
						type: this.bookDetail.type,
						writer: this.bookDetail.writer,
						is_over: this.bookDetail.is_over,
						image: this.bookDetail.image,
						first_chapter_id: this.bookDetail.first_chapter_id,
						last_chapter_id: this.bookDetail.last_chapter_id,
						intro: this.bookDetail.intro
					}
					uni.setStorageSync("bookList", JSON.stringify(_bookList));
				}
			},
			// 查询历史阅读
			getLastReadChapter() {
				let bookList = uni.getStorageSync("bookList");
				if (bookList) {
					let _bookList = JSON.parse(bookList);
					if (_bookList[this.bookDetail.id]) {
						if (_bookList[this.bookDetail.id].chapterCount) {
							this.lastReadChapterId = _bookList[this.bookDetail.id].lastReadChapter;
							this.lastReadChapterIndex = _bookList[this.bookDetail.id].lastReadChapterIndex;
						}
					}
				}
			},
			handleToShare() {
				// uni.share({
				// 	provider: "weixin",
				// 	scene: "WXSceneSession",
				// 	type: 0,
				// 	href: "http://uniapp.dcloud.io/",
				// 	title: "uni-app分享",
				// 	summary: "我正在使用HBuilderX开发uni-app，赶紧跟我一起来体验！",
				// 	imageUrl: "https://img-cdn-qiniu.dcloud.net.cn/uniapp/images/uni@2x.png",
				// 	success: function(res) {
				// 		console.log("success:" + JSON.stringify(res));
				// 	},
				// 	fail: function(err) {
				// 		console.log("fail:" + JSON.stringify(err));
				// 	}
				// });
			}
		}

	}
</script>

<style lang="scss" scoped>
	.detail-box {
		.detail-bg {
			position: fixed;
			top: 0;
			left: 0;
			width: 100vw;
			height: 100vh;
			background-repeat: no-repeat;
			background-size: 100vw 100vh;
			filter: blur(40rpx);
		}

		.detail-wrap {
			position: fixed;
			top: 0;
			left: 0;
			width: 100vw;
			height: 100vh;
			background: linear-gradient(0deg,
				rgba(245, 248, 252, 1) 0%,
				rgba(6, 27, 65, 1) 100%);
			opacity: 0.7;
		}

		.detail-content {
			position: relative;
			display: flex;
			flex-direction: column;
			padding: 60rpx 56rpx;
			color: #fff;

			.detail-top {
				display: flex;
				justify-content: space-between;
				margin-bottom: 48rpx;

				.detail-left {
					color: #fff;
					display: flex;
					flex-direction: column;
					justify-content: space-between;

					.detail-main {
						color: #fff;

						.detail-name {
							font-size: 36rpx;
							font-family: Alibaba PuHuiTi;
							font-weight: bold;
							color: rgba(255, 255, 255, 1);
							opacity: 0.85;
						}

						.detail-info {
							display: flex;
							justify-content: space-between;
							align-items: center;
							margin-top: 20rpx;

							.detail-writer {
								font-size: 20rpx;
								font-family: Alibaba PuHuiTi;
								font-weight: bold;
								color: rgba(255, 255, 255, 1);
								opacity: 0.85;

							}

							.detail-over {
								font-size: 18rpx;
								font-family: Alibaba PuHuiTi;
								font-weight: bold;
								color: rgba(255, 255, 255, 1);
								line-height: 28rpx;
								opacity: 0.65;
							}
						}
					}

					.detail-new {
						width: 440rpx;
						font-size: 20rpx;
						font-family: Alibaba PuHuiTi;
						font-weight: bold;
						color: rgba(255, 255, 255, 1);
						line-height: 28rpx;
						opacity: 0.85;
						padding: 26rpx 0;
						border-top: 1rpx solid rgba(255, 255, 255, 0.25);
						border-bottom: 1rpx solid rgba(255, 255, 255, 0.25);
						display: flex;
						justify-content: space-between;
						align-items: center;
					}
				}
			}

			.detail-intro {
				font-size: 22rpx;
				font-family: Alibaba PuHuiTi;
				font-weight: 400;
				color: rgba(255, 255, 255, 1);
				line-height: 36rpx;
				opacity: 0.65;
			}
		}

		.detail-list {
			padding: 0 40rpx;

			.list-nav {
				display: flex;
				justify-content: space-between;
				align-items: center;
				padding: 42rpx 40rpx;
				position: relative;
				background: rgba(255, 255, 255, 1);
				border-radius: 23rpx 23rpx 0 0;

				text {
					font-size: 40rpx;
					font-family: Alibaba PuHuiTi;
					font-weight: bold;
					color: rgba(6, 27, 65, 1);
					opacity: 0.75;
				}

				text:last-child {
					font-size: 26rpx;
					font-family: Alibaba PuHuiTi;
					font-weight: 400;
					text-decoration: underline;
					color: rgba(146, 200, 255, 1);
				}
			}

			.list-content {
				background: white;
				position: relative;
				height: 70vh;
				overflow: scroll;
				margin-bottom: 140rpx;
				border-radius: 0 0 23rpx 23rpx;

				.list-item {
					position: relative;
					font-size: 28rpx;
					font-family: Alibaba PuHuiTi;
					font-weight: 400;
					color: #061B41;
					margin: 0 40rpx 0 84rpx;
					padding: 36rpx 0;
					border-bottom: 2rpx solid rgba(6, 27, 65, 0.08);
					display: flex;
					align-items: center;
				}

				.active-item {
					position: relative;
					font-size: 28rpx;
					font-family: Alibaba PuHuiTi;
					font-weight: 400;
					color: #92C8FF;
					margin: 0 40rpx 0 84rpx;
					padding: 36rpx 0;
					border-bottom: 2rpx solid rgba(6, 27, 65, 0.08);
					display: flex;
					align-items: center;
				}

				.read-item {
					position: relative;
					font-size: 28rpx;
					font-family: Alibaba PuHuiTi;
					font-weight: 400;
					color: rgba(6, 27, 65, 0.25);
					margin: 0 40rpx 0 84rpx;
					padding: 36rpx 0;
					border-bottom: 2rpx solid rgba(6, 27, 65, 0.08);
					display: flex;
					align-items: center;
				}

				.list-item::before {
					content: '';
					width: 20rpx;
					height: 20rpx;
					border-radius: 20rpx;
					border: 6rpx solid #061B41;
					position: absolute;
					left: -46rpx;
					top: 44rpx;
				}

				.active-item::before {
					content: '';
					width: 20rpx;
					height: 20rpx;
					border-radius: 20rpx;
					border: 6rpx solid #92C8FF;
					position: absolute;
					left: -46rpx;
					top: 44rpx;
				}
			}
		}

		.detail-bottom {
			position: fixed;
			bottom: 0;
			left: 0;
			width: 100%;
			height: 100rpx;
			display: flex;
			justify-content: space-between;
			padding: 16rpx 34rpx;
			font-size: 28rpx;
			align-items: center;
			background: rgba(255, 255, 255, 1);
			box-shadow: 0rpx 0rpx 23rpx 0rpx rgba(6, 27, 65, 0.16);
			border-radius: 40rpx 40rpx 0rpx 0rpx;

			.add-shelf {
				width: 50%;
				text-align: center;
			}

			.read-start {
				width: 95%;
				height: 68rpx;
				background: rgba(145, 199, 255, 1);
				border-radius: 50rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				color: white;
			}
		}
	}
</style>
